package com.xdxc.service.strategy.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xdxc.exception.CustomException;
import com.xdxc.model.dto.AnswerForm;
import com.xdxc.model.dto.QuestionForm;
import com.xdxc.model.entity.Answer;
import com.xdxc.model.entity.CorrectAnswer;
import com.xdxc.model.entity.Question;
import com.xdxc.service.AnswerService;
import com.xdxc.service.CorrectAnswerService;
import com.xdxc.service.QuestionService;
import com.xdxc.service.strategy.QuestionTypeStrategy;
import com.xdxc.utils.ExcelColumnConverter;
import com.xdxc.vo.QuestionWithOptionsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

@Component
public class TrueFalseStrategy implements QuestionTypeStrategy {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private CorrectAnswerService correctAnswerService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleQuestion(QuestionForm questionForm) {
        // 1. 参数校验
        if (questionForm == null || questionForm.getOptions().size()!=2) {
            throw new CustomException(400, "数据有误");
        }

        // 2. 生成唯一ID（替换为分布式ID生成器）
        Snowflake randomIdGenerator=new Snowflake(1, 2);
        Long questionId = randomIdGenerator.nextId();
        // 3. 保存题目信息
        Question question = createQuestionFromForm(questionForm, questionId);

        questionService.save(question);
        // 4. 处理选项答案
        List<Answer> answerList = new ArrayList<>();
        List<Long> correctOptionIds = new ArrayList<>();
        List<AnswerForm>  options= questionForm.getOptions();

        IntStream.range(0, options.size()).forEach(i -> {
            AnswerForm option = options.get(i);
            Long optionId = randomIdGenerator.nextId();
            Answer answer = new Answer();
            answer.setId(optionId);
            answer.setAnswerId(optionId);
            answer.setContent(option.getContent());
            answer.setAbc(ExcelColumnConverter.convertToExcelColumn(i + 1));
            answer.setSort(i + 1);
            answer.setQuId(questionId);
            answerList.add(answer);
            if (option.getChecked()) {
                correctOptionIds.add(optionId);
            }
        });
        if (correctOptionIds.size() != 1){
            throw new CustomException(405,"数据错误");
        }
        // 5. 批量保存答案
        answerService.saveBatch(answerList);
        // 6. 保存正确答案
        CorrectAnswer correctAnswer = new CorrectAnswer();
        correctAnswer.setQuestionId(questionId);
        correctAnswer.setAnswerVersion(1);
        correctOptionIds.sort(Long::compareTo);  // 确保选项顺序一致性
        correctAnswer.setOptionIds(correctOptionIds);
        correctAnswerService.save(correctAnswer);
        return true;
    }

    /**
     *
     *
     * @return Boolean
     */


    @Override
    public Boolean updateQuestion(QuestionForm questionForm) {
        // 1. 参数校验
        if (questionForm == null || questionForm.getOptions().size()!=2) {
            throw new CustomException(400, "数据有误");
        }

        Long questionId = questionForm.getId();

        // 3. 保存题目信息
        Question question = createQuestionFromForm(questionForm,  questionId);

        questionService.updateById(question);

        // 4. 处理选项答案
        List<Answer> answerList = new ArrayList<>();
        List<Long> correctOptionIds = new ArrayList<>();
        List<AnswerForm>  options= questionForm.getOptions();

        IntStream.range(0, options.size()).forEach(i -> {
            AnswerForm option = options.get(i);
            Answer answer = new Answer();
            answer.setId(option.getId());
            answer.setAnswerId(option.getId());

            answer.setContent(option.getContent());
            answer.setAbc(option.getAbc());

            answer.setSort(option.getSort());
            answer.setQuId(questionId);
            answerList.add(answer);
            if (option.getChecked()) {
                correctOptionIds.add(option.getId());
            }
        });


        if (correctOptionIds.isEmpty()){
            throw new CustomException(405,"数据错误");
        }
        // 5. 批量保存答案
        answerService.updateBatchById(answerList);
        // 6. 保存正确答案
        CorrectAnswer correctAnswer = new CorrectAnswer();
        correctAnswer.setQuestionId(questionId);
        correctAnswer.setAnswerVersion(1);
        correctOptionIds.sort(Long::compareTo);  // 确保选项顺序一致性
        correctAnswer.setOptionIds(correctOptionIds);

        correctAnswerService.update(correctAnswer,new LambdaQueryWrapper<CorrectAnswer>().eq(CorrectAnswer::getQuestionId, questionId));
        return true;
    }

    private Question createQuestionFromForm(QuestionForm form, Long questionId) {
        if (form.getContent().trim().equals("<p></p>")){
            throw new CustomException(405,"数据错误");
        }
        Question question = new Question();
        question.setId(questionId);
        question.setQuTypeDictText("判断题");
        question.setQuId(questionId);
        question.setContent(form.getContent());
        question.setQuType(form.getQuType());
        question.setAnswerOrder(Integer.valueOf(form.getDifficulty()));
        question.setAnalysis(form.getAnalyse());
        return question;
    }
}
